package com.ciwong.epaper.modules.pad.homeworkwidget.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.pad.homeworkwidget.common.AppWidgetConstants;
import com.ciwong.epaper.modules.pad.homeworkwidget.presenter.DataProvider;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;


class HomeworkListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {

    private static final String TAG = "HomeworkListRemoteViewsFactory";

    private static final int VIEW_TYPE_COUNT = 1;
    private static final String HAS_DONE = "已完成";
    private static final String HAS_NOT_DONE = "未完成";

    private List<MyWork> mHomeworkList = new ArrayList<MyWork>();

    private Context mContext;

    public HomeworkListRemoteViewsFactory(Context context, Intent intent) {
        this.mContext = context;
        System.out.println("HomeworkListRemoteViewsFactory");
    }

    @Override
    public void onCreate() {
        System.out.println("getHomeWorks");
    }

    @Override
    public int getCount() {
        if (mHomeworkList == null) {
            return 0;
        }
        System.out.println("getHomeWorks");
        return mHomeworkList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private MyWork getHomeWorks(int index) {
        System.out.println("getHomeWorks");
        return mHomeworkList.get(index);
    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @SuppressLint("NewApi")
    @Override
    public RemoteViews getViewAt(int position) {

        if (getCount() == 0) {
            return null;
        }

        System.out.println("getViewAt");
        MyWork newsItem = getHomeWorks(position);
        return applyHomeworkBeanView(mContext, newsItem);
    }

    /**
     * 设置字体大小
     *
     * @param views
     * @param viewId
     * @param textSize
     */
    @SuppressLint("NewApi")
    private void setRemoteViewsTextSize(RemoteViews views, int viewId, int textSize) {
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            // 低版本不支持字体适配
            views.setTextViewTextSize(viewId, TypedValue.COMPLEX_UNIT_SP, textSize / 2);
        }
    }

    @Override
    public int getViewTypeCount() {
        System.out.println("getViewTypeCount" + VIEW_TYPE_COUNT);
        return VIEW_TYPE_COUNT;
    }

    @Override
    public boolean hasStableIds() {
        System.out.println("hasStableIds");
        return true;
    }

    @Override
    public void onDataSetChanged() {
        mHomeworkList = getHomeWorks();
    }

    private List<MyWork> getHomeWorks() {
        return DataProvider.getHomeworkList();
    }

    @Override
    public void onDestroy() {
        System.out.println("onDestroy");
        mHomeworkList.clear();
    }

    /**
     * 创建每个item中的view
     *
     * @param myWork
     * @return
     */
    public static RemoteViews applyHomeworkBeanView(Context context, final MyWork myWork) {
        if (myWork == null) {
            return null;
        }
        RemoteViews viewsContainer = new RemoteViews(context.getPackageName(), R.layout.widget_item_homework);
        RemoteViews viewsHead = new RemoteViews(context.getPackageName(), R.layout.widget_item_textview_head);

        viewsContainer.removeAllViews(R.id.ll_widget_item_container);

        viewsHead.setViewVisibility(R.id.ll_item_head, View.VISIBLE);
        viewsHead.setTextViewText(R.id.tv_item_group_data, CWUtils.getWidgetWorkTimeDay(myWork.getSendDate() * 1000));
        viewsHead.setTextViewText(R.id.tv_item_group_time, CWUtils.getWidgetWorkTimeHour(myWork.getSendDate() * 1000));
        if (null == myWork.getBookName() || "".equals(myWork.getBookName())) {
            viewsHead.setViewVisibility(R.id.tv_item_group_book_name, View.GONE);
        } else {
            viewsHead.setTextViewText(R.id.tv_item_group_book_name, myWork.getBookName());
        }
        viewsContainer.addView(R.id.ll_widget_item_container, viewsHead);

        //遍历添加子作业条目
        addMyWorkContents(context, viewsContainer, myWork);

        Intent fillInIntent = new Intent();
        Bundle extras = new Bundle();
        extras.putString(AppWidgetConstants.WIDGET_HOMEWORK_ITEM_DATA, myWork.getWorkId());
        fillInIntent.putExtras(extras);
        // 设置 第position位的"视图"对应的响应事件, api 11
        viewsContainer.setOnClickFillInIntent(R.id.ll_widget_item_container, fillInIntent);
        return viewsContainer;
    }

    private static void addMyWorkContents(Context context, RemoteViews viewsContainer, MyWork myWork) {
        if (myWork.getWorkContents() == null) return;
        List<WorkContents> workContents = myWork.getWorkContents();
        RemoteViews viewContent = null;
        if (workContents.size() > 0) {
            for (int i = 0; i < workContents.size(); i++) {
                WorkContents workContent = workContents.get(i);
                viewContent = new RemoteViews(context.getPackageName(), R.layout.widget_item_textview_content);
                if (judgeHomeworkItemState(workContent).equals(HAS_DONE)) {//已完成
                    viewContent.setTextViewText(R.id.tv_homework_state, HAS_DONE);
                    String specialTypeState = specialType(workContent);
                    if (!TextUtils.isEmpty(specialTypeState)) {//判断 听说模考 在线做答 状态
                        viewContent.setTextViewText(R.id.tv_homework_state, specialTypeState);
                    }
                    viewContent.setTextColor(R.id.tv_homework_state, context.getResources().getColor(R.color.color_light_green));
                } else {//未完成
                    viewContent.setTextViewText(R.id.tv_homework_state, HAS_NOT_DONE);
                    viewContent.setTextColor(R.id.tv_homework_state, context.getResources().getColor(R.color.color_ffffff));
                }
                setItemHeadBitmap(viewContent, workContent, R.id.iv_item_content_icon);

                viewContent.setTextViewText(R.id.tv_item_text_content, workContent.getResourceName());
                viewsContainer.addView(R.id.ll_widget_item_container, viewContent);
            }
        }
    }

    private static void setItemHeadBitmap(RemoteViews viewContent, WorkContents workContent, int resId) {
        int iconId = R.mipmap.ic_widget_item_listen_exam;
        if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT || workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT) {
            iconId = R.mipmap.ic_widget_item_follow_up;
        } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_DICTATION) { //模块ID:报听写
            iconId = R.mipmap.ic_widget_item_listen_write;
        } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) { //模块ID:听说模考
            iconId = R.mipmap.ic_widget_item_listen_exam;
        } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN ||
                workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_VIDEO_EXPLAIN_NEW) { //视频讲解
            iconId = R.mipmap.ic_widget_item_video;
        } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) { //在线作答
            iconId = R.mipmap.ic_widget_item_online_answer;
        } else if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL) { //互动教程
            iconId = R.mipmap.ic_widget_item_interaction;
        } else {
            iconId = R.mipmap.ic_widget_item_listen_exam;
        }
        viewContent.setImageViewResource(resId, iconId);
    }

    private static String specialType(WorkContents workContent) {
        String specialTypeState = "";
        if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {//听说模考
            if (workContent.workStatus == EpaperConstant.SCORE_STATUS_UNCOMPLETE) {
                specialTypeState = "评分中";
            } else if (workContent.workStatus == EpaperConstant.SCORE_STATUS_TSMK_UNCOMPLETE) {
                specialTypeState = "批改中";
            }
        } else if (workContent.moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER) {//在线作答
            if (workContent.workStatus == EpaperConstant.SCORE_STATUS_TSMK_UNCOMPLETE
                    || workContent.workStatus == EpaperConstant.SCORE_STATUS_ONLINEANSWER_UNCOMPLETE) {
                specialTypeState = "批改中";
            }
        }
        return specialTypeState;
    }

    private static String judgeHomeworkItemState(WorkContents workContent) {
        String homeworkitemState = HAS_NOT_DONE;
        int requireReadTimes = -1;
        boolean isSubmit = false;
        if (workContent.getDoWorkId() != null && workContent.getDoWorkId().length() > 0) {
            isSubmit = true;
        }
        if (workContent.getSubmitCount() > 0 && isSubmit) {//提交过作业
            String str_requirementContent = workContent.requirementContent;
            if (workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT
                    || workContent.getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_SENTENCE_REPEAT
                    && !TextUtils.isEmpty(str_requirementContent)) {//当是跟读类型作业（单独处理）
                try {
                    RequirementContent requirementContent = new Gson().fromJson(str_requirementContent, RequirementContent.class);
                    requireReadTimes = requirementContent.getReadtimes();
                    if (requireReadTimes <= workContent.getSubmitCount()) {
                        homeworkitemState = HAS_DONE;
                    } else {//当是跟读类型以外作业（没有次数要求，做过一次就完成了）
                        homeworkitemState = HAS_NOT_DONE;
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            } else {
                homeworkitemState = HAS_DONE;
            }
        } else {//未提交过作业
            homeworkitemState = HAS_NOT_DONE;
        }
        return homeworkitemState;

    }
}